//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Project: Money System
// Purpose: Allows deployment of economies in **any** game type that does not already have an economy
// Version: 0.2a
// Author: Max Bainrot (aka Mr Puffy) 
// Installation: Whack the sucker in your addons folder
//////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Data Structure _note this is here for historical reasons, garry fucked it in rev 54
//////////////////////////////////////////////////////////////////////////////////////////////////////////

// Money System Folder Structure
// base_dir => data/money
// wallet => data/money/wallet

//Wallet file
// filename: <steamid>.txt
// contents: number (current wallet value)

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// SQL Database/Table Structure
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// table: moneymod_wallet
// structure: id (autoinc,int), steamid (string), amount (double)

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function List
//////////////////////////////////////////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////////////////////////////////////////
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Start of the real shit !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //
//////////////////////////////////////////////////////////////////////////////////////////////////////////

// FILE REPLICATION (so that clients GET the god damn user interface...)

if SERVER then
AddCSLuaFile("autorun/client/money_gui.lua");
else 
return
end

//if file.Exists("../lua/moneymod/.svn/entries") then
//	MMVersion = tonumber( string.Explode( "\n", file.Read( "../lua/moneymod/.svn/entries" ) )[ 4 ] ) --get svn revision, stolen from ULX
//else
//	MMVersion = 0	--change this value to the current revision number when making a general release
//end

// Commented it out due to it not updating with every commit :|

// INIT Metatable (as it makes life easy)
local meta = FindMetaTable("Player")

  ////////////////////////////////////////////////////////////////////////////////////////////////
 // Core/UTIL
////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////
// Function: GetPlyFile(ply)
// Purpose: Gets the player's steamid and converts it to a filesystem friendly format
////////////////////////////////////////////////////////////////////////////////////////////////

function GetPlyFile(ply)
local playersteamid = ply:SteamID()
local plyfile = playersteamid
plyfile = string.Replace(plyfile,":","")
return plyfile
end


////////////////////////////////////////////////////////////////////////////////////////////////
// Function: Init()
// Purpose: Sets the server up for first use :)
////////////////////////////////////////////////////////////////////////////////////////////////
function Init()

//CREATE DATA HIARCHY IF NOT ALREADY DONE
//////// ALL THIS WAS FUCKED BY GARRY :@, CHEERS MATE! (not)
/*
// data/money
if (not file.IsDir("money")) then
  file.CreateDir("money")
end 

// data/money/wallet
if (not file.IsDir("money/wallet")) then
  file.CreateDir("money/wallet")
end 
*/

/////
///// Beginning of feeling my way through a browthal as a blind man
/////
Msg("Money Mod CORE Loading...\n");

Msg("[MoneyMod] Checking Intregity of the SQL Lite Database\n");

if (!sql.TableExists("moneymod_wallet")) then 
	Msg("[MoneyMod] the table moneymod_wallet is missing!, recreating\n");
	sql.Begin()
	local res = sql.Query("CREATE TABLE `moneymod_wallet` (id INT AUTO_INCREMENT, steamid STRING, money DOUBLE)")
	sql.Commit()
end

//Msg("SVN Version: " .. MMVersion .. "\n");
end

function MoneyModSQL_PlayerExists(ply)
	local plyfile = GetPlyFile(ply)
	local res = sql.Query("SELECT * FROM `moneymod_wallet` WHERE steamid = \"" .. plyfile .. "\" LIMIT 1");
	
	if (!res) then return false end
	
	return true
	
end

function MoneyModSQL_SetPlayerWallet(ply,amount)
	local plyfile = GetPlyFile(ply)
	sql.Begin()
	if MoneyModSQL_PlayerExists(ply) then
		local res = sql.Query("UPDATE `moneymod_wallet` SET `money`='" .. tonumber(amount) .. "' WHERE `steamid`=\"" .. plyfile .. "\"");
	end
	sql.Commit( )
end

function MoneyModSQL_CreatePlayer(ply)
	local plyfile = GetPlyFile(ply)
	sql.Begin()
	local res = sql.Query("INSERT INTO `moneymod_wallet` (steamid,money) VALUES (\"".. plyfile .. "\",1000)");
	sql.Commit( )
end

    ////////////////////////////////////////////////////////////////////////////////////////////////
   // 
  // Meta shit
 //
//////////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////
// function: MoneyMod_InitSpawn()
// Purpose: Initilises MoneyMod Data for the player's session
////////////////////////////////////////////////////////////////////////////////////////////////

function meta:MoneyMod_InitSpawn()

if (CLIENT) then return end

local plyfile = GetPlyFile(self)

if(MoneyModSQL_PlayerExists(self)) then
// We exist, load money and setup networked var 
self:SetNetworkedInt("money",tonumber(self:MoneyMod_CurrentFunds()))
else
MoneyModSQL_CreatePlayer(self)
sql.Commit()
self:SetNetworkedInt("money",1000) // Saved 1 File i/o call :)
end

end


////////////////////////////////////////////////////////////////////////////////////////////////
// function: MoneyMod_GiveMoney(amount)
// Purpose: Give player money (e.g. salary)
////////////////////////////////////////////////////////////////////////////////////////////////

function meta:MoneyMod_GiveMoney(amount)
if (CLIENT) then return end // serverside only, sry peeps

local plyfile = GetPlyFile(self)

local cfunds = self:MoneyMod_CurrentFunds()

local newfunds = cfunds + amount

MoneyModSQL_SetPlayerWallet(self,newfunds)
sql.Commit()
self:SetNetworkedInt("money",newfunds)
end

////////////////////////////////////////////////////////////////////////////////////////////////
// function: MoneyMod_CurrentFunds()
// Purpose: returns current funds
////////////////////////////////////////////////////////////////////////////////////////////////

function meta:MoneyMod_CurrentFunds()
if CLIENT then return end // server side only, sry hax0rs

local plyfile = GetPlyFile(self)

	local res = sql.Query("SELECT * FROM `moneymod_wallet` WHERE steamid = \"" .. plyfile .. "\" LIMIT 1");
	
	if (!res) then return false end
	
	for id, row in pairs (res) do
		return tonumber(row['money'])
	end

end 

////////////////////////////////////////////////////////////////////////////////////////////////
// function: MoneyMod_TakeMoney(amount)
// Purpose: Takes a players money :) (i.e. tax)
////////////////////////////////////////////////////////////////////////////////////////////////

function meta:MoneyMod_TakeMoney(amount)
if (CLIENT) then return end // serverside only, sry peeps

//local plyfile = GetPlyFile(self)

local cfunds = self:MoneyMod_CurrentFunds()

local newfunds = cfunds - amount

MoneyModSQL_SetPlayerWallet(self,newfunds)
sql.Commit()
self:SetNetworkedInt("money",newfunds)
end

////////////////////////////////////////////////////////////////////////////////////////////////
// function MoneyMod_PayThem(targetid, amount)
// Purpose: Funds transfer from A to B
// targetid = "player object based upon his entity index"
// amount = "DUH!"
////////////////////////////////////////////////////////////////////////////////////////////////

function meta:MoneyMod_PayThem(targetid, amount)
if (CLIENT) then return end // serverside only, sry peeps

local target = player.GetByID(targetid)

if (target == nil) then return end
if !(target.IsPlayer()) then return end

Msg("Target ID " .. targetid .. " is " .. target:GetName() .. "\n")

local sendfile = GetPlyFile(self)
local rcptfile = GetPlyFile(target)

local sfunds = self:MoneyMod_CurrentFunds()
local rfunds = target:MoneyMod_CurrentFunds()

if (sfunds < tonumber(amount)) then
self:PrintMessage( HUD_PRINTTALK,"Insuffient Funds!")
else
// funds transfer!!
target:MoneyMod_GiveMoney(amount)
self:MoneyMod_TakeMoney(amount)
// Send da pops!
target:PrintMessage( HUD_PRINTTALK,self:GetName() .. " gave you " .. amount)
self:PrintMessage( HUD_PRINTTALK,"You just gave " .. amount .. " to " .. target:GetName())
end
end

//Player:EntID( )


    ////////////////////////////////////////////////////////////////////////////////////////////////
   // 
  // Game hooks, init, etc
 //
//////////////////////////////////////////////////////////////////////////////////////////////////

/// INIT
Init()

include("../shared.lua")